package net.confinanz.connection.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

import net.confinanz.config.ServerConfig;
import net.confinanz.server.ServerCore;

public class ServerConnector {

	private boolean interrupted;
	
	private ServerCore core;
	private ServerConfig config;
	private Vector<Connection> connections;

	
	public ServerConnector(ServerCore core, ServerConfig config) {
		this.core = core;
		this.config = config;
		this.interrupted = false;
		this.connections = new Vector<Connection>( this.config.getMaxConnections() );
		
		try {
			listen();
		} catch (IOException e) {
			// TODO
		}
	}
	
	public void listen() throws IOException {
		ServerSocket server = new ServerSocket( this.config.getServerPort() );
		
		while (!isInterrupted()) {
			Socket client = null;

			if  ( this.connections.size() < this.config.getMaxConnections() ) {
				try {
					client = server.accept();
					new Connection(client, this);
				} catch (IOException e) {
					// TODO
				}
			}
		}
	}
	
	public Vector<Connection> getConnections() {
		return this.connections;
	}

	private boolean isInterrupted() {
		return this.interrupted;
	}
	
	public ServerCore getCore() {
		return this.core;
	}
}